package com.ykdl.member;

import java.io.File;
import java.util.List;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Handler;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import cn.jpush.android.api.JPushInterface;

import com.baidu.location.LocationClient;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.umeng.analytics.MobclickAgent;
import com.ykdl.member.kid.R;
import com.ykdl.member.base.GlobalContext;
import com.ykdl.member.base.QLog;
import com.ykdl.member.kid.beans.BabyProfileBean;
import com.ykdl.member.kid.beans.ProfileBean;
import com.ykdl.member.kid.prefs.MyPrefs;
import com.ykdl.member.kid.util.LocationUtils;
import com.ykdl.member.kid.util.MobileUtils;
import com.ykdl.member.kid.util.MyUser;
import com.ykdl.member.kid.util.ResoureUtil;

/**
 * 
 * 目的：当出现未捕捉的异常时，打印log，并且 重启应用
 * <p>
 * detailed comment
 * 
 * @author yangrunfei 2012-3-14
 * @see
 * @since 1.0
 */
public class KidApp extends Application implements
		Thread.UncaughtExceptionHandler {
	static int count = 0;
	private static KidApp instance = null;
	private float scaleDensity;// 设备的像素点
	public static int SCREEN_WIDTH = -1;
	public static int SCREEN_HEIGHT = -1;
	public static final int SCREEN_SMALL = 1;
	public static final int SCREEN_BIG = 2;
	public static final int SCREEN_NORMAL = 3;
	public static int SCREEN_TYPE = 3;
	public static String IMAGE_TYPE = "m";// m或者是L m小图，L，大图

	public int gridview_item_gift_height = 0;

	public static int share_data_twoimg_wid = 0;
	public static int share_data_twoimg_hei = 0;

	public static int share_data_threeimg_topwid = 0;
	public static int share_data_threeimg_tophei = 0;

	public static int share_data_threeimg_botwid = 0;
	public static int share_data_threeimg_bothei = 0;

	/**
	 * 当账号已在其他设备登上时，进行强制登录时，执行活动时，返回反馈的结果标示 1.false:取消强制登录 2.true：强制登录成功
	 */
	public boolean isRefreshDataForLoginFoce = false;
	public boolean isFromSyncDataReceiver = false;

	public static int share_data_oneimg_wid = 0;
	public static int share_data_oneimg_hei = 0;

	public static int share_data_oneimg_wid_big = 0;
	public static int share_data_oneimg_hei_big = 0;
	public static int gift_hight_big = 0;

	public Handler handler = new Handler();
	private AppManager  mAppManager;

	public MyUser mMyUser = null;
	private ProfileBean mProfile;
	private BabyProfileBean mBabyProfiel;
	public static final String APP_KEY = "y745wfm84itzv";
	public static KidApp getInstance() {
		return instance;
	}
	 public LocationClient mLocationClient;
	public void runOnUIThread(Runnable runnable) {
		handler.post(runnable);//将子线程添加到了主线程队列中
	}
	public AppManager getAppManager()
	{
		if (mAppManager == null)
		{
			mAppManager = AppManager.getAppManager();
		}
		return mAppManager;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		instance = this;
		mMyUser = new MyUser(this);
		if (SCREEN_TYPE == -1 || SCREEN_TYPE == 0) {
			Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
					.getDefaultDisplay();

			SCREEN_WIDTH = display.getWidth();
			SCREEN_HEIGHT = display.getHeight();
			if (SCREEN_HEIGHT <= 800) {
				gift_hight_big = 480;
			} else if (SCREEN_HEIGHT == 1280) {
				gift_hight_big = 780;
			} else {
				gift_hight_big = 780;
			}
			if (SCREEN_WIDTH == 320) {
				SCREEN_TYPE = SCREEN_SMALL;
				IMAGE_TYPE = "m";
				share_data_oneimg_wid = 160;
				share_data_oneimg_hei = 160;

				share_data_oneimg_wid_big = 160;
				share_data_oneimg_hei_big = 160;

			} else if (SCREEN_WIDTH >= 720) {
				SCREEN_TYPE = SCREEN_BIG;
				IMAGE_TYPE = "L";
				share_data_oneimg_wid = 240;
				share_data_oneimg_hei = 240;

				share_data_oneimg_wid_big = 400;
				share_data_oneimg_hei_big = 400;

			} else {
				IMAGE_TYPE = "m";
				SCREEN_TYPE = SCREEN_NORMAL;
				share_data_oneimg_wid = 160;
				share_data_oneimg_hei = 160;

				share_data_oneimg_wid_big = 360;
				share_data_oneimg_hei_big = 360;

			}

		}
		JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
		Thread.setDefaultUncaughtExceptionHandler(this);
		ResoureUtil.intiResoure(this.getResources());
		GlobalContext.init(this);
		MobclickAgent.updateOnlineConfig( this );
		QLog.init();
		initImageLoader(this);
		// 获得手机设备的像素点
		scaleDensity = MobileUtils.getDeviceDisplayMetrics(this).density;
 //需要的时候，放开就好了
//		getLocation();
		mLocationClient = LocationUtils.getInstance(this).mLocationClient;
	}

	/**
	 * 获得手机设备的像素点
	 * 
	 * @return
	 */
	public float getScaleDensity() {
		return scaleDensity;
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		ex.printStackTrace();
		MyPrefs.increateForceExit(this);
		StackTraceElement[] se = ex.getStackTrace();
		QLog.error("KidApp  uncaughtException" + ex.toString());
		for (int i = 0; i < se.length; i++) {
			QLog.error("KidApp", se[i].toString());
		}
		System.exit(2);

	}

	/**
	 * 判断程序是否正在前台运行
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isTopActivity(Context context) {
		String mypackage = "com.ykdl.member.kid";
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);

		List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);

		if (tasksInfo.size() > 0) {
			// 应用程序位于堆栈的顶层
			if (mypackage.equals(tasksInfo.get(0).topActivity.getPackageName())) {
				return true;
			}

		}

		return false;

	}

	public boolean isRefreshDataForLoginFoce() {
		return isRefreshDataForLoginFoce;
	}

	public void setRefreshDataForLoginFoce(boolean isRefreshDataForLoginFoce) {
		this.isRefreshDataForLoginFoce = isRefreshDataForLoginFoce;
	}

	public boolean isFromSyncDataReceiver() {
		return isFromSyncDataReceiver;
	}

	public void setFromSyncDataReceiver(boolean isFromSyncDataReceiver) {
		this.isFromSyncDataReceiver = isFromSyncDataReceiver;
	}

	
	public void setCurrentActivity(Activity activity){
		
	}
	
	public static void initImageLoader(Context context) {
		File cacheDir = StorageUtils.getOwnCacheDirectory(context,
				"hshCache");// 获取到缓存的目录地址
		// 创建配置ImageLoader(所有的选项都是可选的,只使用那些你真的想定制)，这个可以设定在APPLACATION里面，设置为全局的配置参数
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context)
				// 线程池内加载的数量
				.threadPoolSize(3).threadPriority(Thread.NORM_PRIORITY - 2)
				.memoryCache(new WeakMemoryCache())
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				// 将保存的时候的URI名称用MD5 加密
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.discCache(new UnlimitedDiscCache(cacheDir))// 自定义缓存路径
				// .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
				.writeDebugLogs() // Remove for release app
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);// 全局初始化此配置
	}
}
